package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.PubLib;
import com.rk.kbk.dao.SortBetweenDao;
import com.rk.kbk.dao.SortTypeDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.SortBetween;
import com.rk.kbk.model.SortType;
import com.rk.kbk.model.User;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @SortBetweenController
 * @类型中间Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/sortBetween")
public class SortBetweenController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private SortBetweenDao sortBetweenDao;
    @Autowired
    private SortTypeDao sortTypeDao;
    @Autowired
    private UserDao userDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加商户类型
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addShopSortBetween",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addShopSortBetween(Long userId,Long sortTypeId){
        log.debug("添加商户类型");
        SortBetween s = new SortBetween();
        User shop = userDao.findOne(userId);
        s.setShop(shop);
        SortType sortType = sortTypeDao.findOne(sortTypeId);
        s.setSortTypeId(sortType);
        s.setType(1);
        sortBetweenDao.save(s);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改类型中间
     * @param sortBetweens
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeSortBetween",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeSortBetween(@RequestBody List<SortBetween> sortBetweens){
        log.debug("批量添加/修改类型中间");
        sortBetweenDao.save(sortBetweens);
        return JsonResp.ok();
    }

    /**
     * @获取类型中间详情-BySortBetweenId
     * @param sortBetweenId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sortBetweenDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findSortBetweenDetailsBySortBetweenId(Long sortBetweenId) {
        log.debug("获取类型中间详情-BySortBetweenId");
        return JsonResp.ok(sortBetweenDao.findOne(sortBetweenId));
    }

    /**
     * @分页查询类型中间(jpa方式)
     * @param sortBetween 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageSortBetweenJpa(@RequestBody(required = false) SortBetween sortBetween, Integer pageNum, Integer pageSize) {
        log.debug("分页查询类型中间(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == sortBetween) {
            page = sortBetweenDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  sortBetween.getUserName();
            page = sortBetweenDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<SortBetween> content = page.getContent();
//        for (SortBetween sortBetween1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除类型中间-one(永久)
     * @param sortBetweenId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSortBetweenOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSortBetweenOne(Long sortBetweenId) {
        log.debug("删除类型中间-one(永久)");
        sortBetweenDao.delete(sortBetweenId);
        return JsonResp.ok();
    }


    /**
     * @根据商家id获取订单类型列表
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findOrderTypeList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOrderTypeList(Long shopId) {
        log.debug("根据商家id获取订单类型列表");
        User shoop=userDao.findOne(shopId);
        List<SortBetween> sortBetweenList=sortBetweenDao.findByTypeAndShopAndOrdersIs(1,shoop,null);
        List<SortType> sortTypeList=new ArrayList<>();
        for(int i=0,y=sortBetweenList.size();i<y;i++){
            SortBetween sortBetween=sortBetweenList.get(i);
                sortTypeList.add(sortBetween.getSortTypeId());
        }
        return JsonResp.ok(sortTypeList);
    }

    /**
     * @批量删除类型中间(永久)
     * @param sortBetweens
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeSortBetween",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeSortBetween(@RequestBody List<SortBetween> sortBetweens) {
        log.debug("批量删除类型中间(永久)");
        sortBetweenDao.delete(sortBetweens);
        return JsonResp.ok();
    }

    /**
     * @获取商品详情和商家类型
     * @param userId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/shopDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findSortBetweenByUserId(Long userId,Integer type) {
        log.debug("获取商品详情和商家类型");
        User user = userDao.findOne(userId);
        return JsonResp.ok(sortBetweenDao.findByTypeAndShopAndOrdersIs(type, user,null));
    }



    /**
     * @获取所有点店家信息
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findAllShop",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAllShop(String shopType,String saleType,String lng,String lat) throws Exception {
        log.debug("获取所有点店家信息");
        String shopTypeList="";
        if(shopType==null || shopType.equals("0")  || "".equals(shopType) || "null".equals(shopType)){
          List<SortType>  sortTypeList=sortTypeDao.findAll();
            for (SortType st:sortTypeList) {
                shopTypeList+=st.getId()+",";
            }
            shopTypeList= shopTypeList.substring(0,shopTypeList.length()-1);
        }else {
            shopTypeList=shopType;
        }
      //  String sql="select distinct shop from sort_between where sort_type_id in ("+sortTypeList+")";

        String sql2="SELECT * FROM (SELECT  DISTINCT d.id,b.nick_name,b.real_name,b.phone,b.store_url,ifnull(b.shop_start_money,0.00) as starting_price,c.province,c.city,c.county,c.address_detail, FORMAT(6378.138*2*" +
                " ASIN(" +
                "SQRT(" +
                "POW(SIN(("+lat+"*PI()/180-c.lat*PI()/180)/2),2)+" +
                "COS("+lat+"*PI()/180)*COS(c.lat*PI()/180)*POW(SIN(("+lng+"*PI()/180-c.lng*PI()/180)/2),2)" +
                ")" +
                "),2)AS distance, COUNT(DISTINCT d.id) AS sum FROM sort_between a,user b,address c,orders d " +
                "WHERE a.shop=b.id AND b.address=c.id AND b.id=d.shop AND  d.order_status!=0 AND a.sort_type_id IN ("+shopTypeList+") GROUP BY b.id ) a" +
                " WHERE a.distance<5";

        //然后 对所有满足查询条件的商家按销量或距离排序
        if(saleType!=null && !"null".equals(saleType)){
            if(saleType.equals("-1")){//按销量
                sql2+=" order by a.sum desc";
            }else if(saleType.equals("-2")){//按距离
                sql2+=" order by a.distance asc";
            }
        }
        Query query = entityManager.createNativeQuery(sql2);
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        return JsonResp.ok(mapList);
    }


}
